/**
* @CopyRight xinweitech.cn
* @author wuyahui
* @E-mail wuyahui0124505@163.com
* @version 1.0.0
* @Date  2015年4月3日 下午1:03:40
*/
package com.tstudy.laoshibang.login;

import java.util.HashMap;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.apache.http.Header;
import org.json.JSONObject;

import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;
import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.base.BaseActivity;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.BaseFragment;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.base.HttpManager;
import com.tstudy.laoshibang.event.UpdateLoginStatusEvent;
import com.tstudy.laoshibang.manager.UserManager;
import com.tstudy.laoshibang.mode.User;
import com.tstudy.laoshibang.mode.response.BaseResponse;
import com.tstudy.laoshibang.mode.response.UserResponse;
import com.tstudy.laoshibang.share.BaseUIListener;
import com.tstudy.laoshibang.share.WrapQQ;
import com.tstudy.laoshibang.share.WrapSinaWeibo;
import com.tstudy.laoshibang.share.WrapWechat;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;
import com.tstudy.laoshibang.utils.SharedPreferencesUtil;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;
import de.greenrobot.event.EventBus;
@SuppressLint("HandlerLeak")
@EFragment(R.layout.login)
public class LoginFragment extends BaseFragment{
	final static String TAG = "login";
	public LoginFragment() {
		super();
	}
	
	@ViewById(R.id.login_root)
	RelativeLayout mRootLayout;
	
	@ViewById(R.id.login_username)
	EditText mUserNameExt;
	@ViewById(R.id.login_password)
	EditText mPasswordExt;
	
	boolean mIsFirstLoad = true;
	LayoutInflater mInflater;
	String mLoginName;
	String mPassword;
	int mSource;

	public static void add(int containerViewId) {
		Bundle args = new Bundle();
		args.putInt(CONSTANT.ARGS.FRAGMENT_ID, containerViewId);
		Fragment fragment = Fragment.instantiate(BaseApplication.mContext,LoginFragment_.class.getName(),args);
		((BaseActivity) BaseApplication.mCurrentActivity).add(containerViewId, fragment, TAG);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		super.onCreateView(inflater, container, savedInstanceState);
		LogUtil.d("--mBaseLayout==" + mRootLayout);
		mIsFirstLoad = mRootLayout == null;
		if (mRootLayout != null) {
			((ViewGroup) mRootLayout.getParent()).removeAllViews();
		}
		return mRootLayout;
	}
	
	@AfterViews
	public void initView(){
		mRootLayout.setOnClickListener(null);
	}
	
	
	ThirdLoginCallBack mThirdLoginCallBack = new ThirdLoginCallBack() {
		
		@Override
		public void onSuccess(int source, String sourceId, String nick, int sex,
				String url) {
			// TODO Auto-generated method stub
			HashMap<String, String> map = new HashMap<String, String>();
			map.put(CONSTANT.LOGIN_EVENT_TYPE_LAOSHIBANG, CONSTANT.LOGIN_EVENT_TYPE_LAOSHIBANG);
			CommonUtil.umengEvent(CONSTANT.EVENT_ID.LOGIN, map);
			thirdLogin(source, sourceId, nick, sex, url);
		}
		
		@Override
		public void onFailed(String errorMsg) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onAuthComplete(boolean result) {
			// TODO Auto-generated method stub
			
		}
	};
	
	/**
	 * 第三方登陆
	 * @param source
	 * @param sourceId
	 * @param nick
	 * @param sex
	 * @param url
	 */
	public void thirdLogin(final int source, final String sourceId, final String nick, final int sex,
			final String url){
		HashMap<String, String> map = new HashMap<String, String>();
		switch (source) {
		case CONSTANT.USER_SOURCE_WEIBO:
			map.put(CONSTANT.LOGIN_EVENT_TYPE_SINA, CONSTANT.LOGIN_EVENT_TYPE_SINA);
			break;
		case CONSTANT.USER_SOURCE_WECHAT:
			map.put(CONSTANT.LOGIN_EVENT_TYPE_WECHAT, CONSTANT.LOGIN_EVENT_TYPE_WECHAT);
			break;
		case CONSTANT.USER_SOURCE_QQ:
			map.put(CONSTANT.LOGIN_EVENT_TYPE_QQ, CONSTANT.LOGIN_EVENT_TYPE_QQ);
			break;

		default:
			break;
		}
		CommonUtil.umengEvent(CONSTANT.EVENT_ID.LOGIN, map);
		BaseJsonHandler<UserResponse> response = new BaseJsonHandler<UserResponse>() {
			@Override
			public void onStart() {
				showProgressDialog("", "登录中...", 0);
				super.onStart();
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, UserResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (response.getData() != null) {
						User user = response.getData();
						afterLogin(user,source,sourceId);
		             }
				}else {
					if (!TextUtils.isEmpty(response.getErrMsg())) {
						BaseApplication.showToast(response.getErrMsg());
					}
                }
			}
			@Override
			public void onFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) {
				super.onFailure(statusCode, headers, responseBytes, throwable);
				BaseApplication.showToast(throwable.getMessage());
				
			}
			@Override
			protected UserResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,UserResponse.class);
			}
			
		};
		HttpManager.getInstance().thirdLogin(source, sourceId, nick, sex, url, response);
	}
	
	IUiListener userInfoListener = new IUiListener() {
		
		@Override
		public void onError(UiError arg0) {
			// TODO Auto-generated method stub
		}
		
		@Override
		public void onComplete(Object arg0) {
			JSONObject response = (JSONObject)arg0;
			LogUtil.d(response.toString());
//			BaseApplication.showToast(response.toString());
		}
		
		@Override
		public void onCancel() {
			// TODO Auto-generated method stub
			
		}
	};
	
	
	@Click({R.id.login_back,R.id.login_by_laoshibang_action,R.id.login_by_wechat,R.id.login_by_weibo,R.id.login_by_qq,R.id.login_reset_password_action,R.id.login_regist_action})
	public void actionClick(View view){
		switch (view.getId()) {
		case R.id.login_back:
			backAction(mFragmentId);
			break;
		case R.id.login_by_laoshibang_action:
			login();
			break;
		case R.id.login_by_wechat:
			WrapWechat.getInstance().login(mThirdLoginCallBack);
			break;
		case R.id.login_by_weibo:
			WrapSinaWeibo.getInstance().weiboLogin(mThirdLoginCallBack);
			break;
		case R.id.login_by_qq:
			WrapQQ.getInstance().login(LoginFragment.this, new IUiListener() {
				@Override
				public void onError(UiError arg0) {
				}
				
				@Override
				public void onComplete(Object arg0) {
//					BaseApplication.showToast(arg0.toString());
					WrapQQ.getInstance().getUserInfo(new BaseUIListener(BaseApplication.mContext,mHandler,"get_simple_userinfo"));
				}
				@Override
				public void onCancel() {
					
				}
			});
			break;
		case R.id.login_reset_password_action:
			ResetPasswordValidateFragment.add(mFragmentId);
			break;
		case R.id.login_regist_action:
			RegistFragment.add(mFragmentId);
			break;

		default:
			break;
		}
		showSoftKeyBoard(mUserNameExt, false);
		showSoftKeyBoard(mPasswordExt, false);
	}
	private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case BaseUIListener.ON_COMPLETE:
                JSONObject response = (JSONObject)msg.obj;
                String sourceId = WrapQQ.getInstance().mTencent.getQQToken().getOpenId();
                String nick = response.optString("nickname");
                String sexStr = response.optString("gender");
                int sex = "男".equals(sexStr)?CONSTANT.SEX_MALE:CONSTANT.SEX_FEMALE;
                String url = response.optString("figureurl_qq_2");
                thirdLogin(CONSTANT.USER_SOURCE_QQ,sourceId, nick, sex, url);
                break;
            case BaseUIListener.ON_ERROR:
                break;
            case BaseUIListener.ON_CANCEL:
                break;
            }
        }	    
	};
	
	public void login(){
		if (TextUtils.isEmpty(mUserNameExt.getText()) || TextUtils.isEmpty(mPasswordExt.getText())) {
			BaseApplication.showToast(R.string.login_error_username_not_null);
			return;
		}else{
			mLoginName = mUserNameExt.getText().toString();
			mPassword = CommonUtil.getMD5(mPasswordExt.getText().toString());
			mSource = CONSTANT.USER_SOURCE_LAOSHIBANG;
		}
		HashMap<String, String> map = new HashMap<String, String>();
		map.put(CONSTANT.LOGIN_EVENT_TYPE_LAOSHIBANG, CONSTANT.LOGIN_EVENT_TYPE_LAOSHIBANG);
		CommonUtil.umengEvent(CONSTANT.EVENT_ID.LOGIN, map);
		BaseJsonHandler<UserResponse> response = new BaseJsonHandler<UserResponse>() {
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				showProgressDialog("", "登录中...", 0);
				super.onStart();
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, UserResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (response.getData() != null) {
						User user = response.getData();
		                   afterLogin(user,CONSTANT.USER_SOURCE_LAOSHIBANG,"");
		             }
				}else {
                    BaseApplication.showToast(response.getErrMsg());
                }
			}
			@Override
			public void onFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) {
				BaseApplication.showToast(throwable.getMessage());
				super.onFailure(statusCode, headers, responseBytes, throwable);
			}
			@Override
			protected UserResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,UserResponse.class);
			}
		};
		HttpManager.getInstance().login(mLoginName,mPassword, response);
	}
	
	public void afterLogin(User user,int source,String sourceId){
		backAction(mFragmentId);
		BaseApplication.mUserNo = user.userNo;
		user.setMobile(mLoginName);
		user.setPassword(mPassword);
		user.setSource(source);
		user.setSourceId(sourceId);
		user.setMediaSource(CONSTANT.MEDIA_SOURCE_ANDROID);
		user.setRole(CONSTANT.USER_ROLE_TEACHER);
		UserManager.getInstance().loginAction(user);
		EventBus.getDefault().post(new UpdateLoginStatusEvent());
		if (!TextUtils.isEmpty(SharedPreferencesUtil.getClientId(BaseApplication.mContext))) {
			BaseApplication.mPushUserId = SharedPreferencesUtil.getClientId(BaseApplication.mContext);
			bindBaiduPush();
		}
	}
	
	public void bindBaiduPush(){
		BaseJsonHandler response = new BaseJsonHandler<BaseResponse>() {
			@Override
			public void onStart() {
				super.onStart();
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, BaseResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
				}else {
                    BaseApplication.showToast(response.getErrMsg());
                }
			}
			@Override
			protected BaseResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,BaseResponse.class);
			}
		};
		HttpManager.getInstance().bindPush(true, response);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void clear() {
		// TODO Auto-generated method stub
		showSoftKeyBoard(mUserNameExt, false);
		showSoftKeyBoard(mPasswordExt, false);
		
	}

	@Override
	public void initArgs(Bundle args) {
		if (args != null) {
			mFragmentId = args.getInt(CONSTANT.ARGS.FRAGMENT_ID);
		}
	}

}
